package liuwanghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import liuwanghui.constant.OrderStatusConstant;
import liuwanghui.dto.request.*;
import liuwanghui.exception.BusinessException;
import liuwanghui.mapper.SaleOrderMapper;
import liuwanghui.pojo.Result;
import liuwanghui.pojo.SaleOrder;
import liuwanghui.pojo.SaleOrderStatusLog;
import liuwanghui.service.SaleOrderService;
import liuwanghui.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SaleOrderServiceImpl implements SaleOrderService {

    private final SaleOrderMapper saleOrderMapper;
    private final CacheUtil cacheUtil;

    @Override
    public Result getSaleOrders(SaleOrderQueryDTO params) {
        PageHelper.startPage(params.getPage(), params.getPageSize());
        List<SaleOrder> orders = saleOrderMapper.findOrdersBySearch(params);
        return Result.success(new PageInfo<>(orders));
    }

    @Override
    @Transactional
    public Result createOrder(SaleOrderCreateDTO dto) {
        // 1. 创建订单
        SaleOrder order = new SaleOrder();
        order.setOrderNo(generateOrderNo());
        order.setProductId(dto.getProductId());
        order.setQuantity(dto.getQuantity());
        order.setPrice(dto.getPrice());
        order.setTotalAmount(dto.getPrice().multiply(new BigDecimal(dto.getQuantity())));
        order.setStatus(OrderStatusConstant.PENDING);
        order.setReceiverName(dto.getReceiverName());
        order.setReceiverPhone(dto.getReceiverPhone());
        order.setReceiverAddress(dto.getReceiverAddress());
        order.setRemark(dto.getRemark());
        order.setCreateTime(LocalDateTime.now());
        
        saleOrderMapper.insertOrder(order);
        return Result.success(order);
    }

    @Override
    @Transactional
    public void cancelOrder(Long id) {
        SaleOrder order = saleOrderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (!canCancel(order.getStatus())) {
            throw new BusinessException("当前订单状态不允许取消");
        }

        order.setCancelTime(LocalDateTime.now());
        recordStatusChange(order, OrderStatusConstant.CANCELLED, "consumer", "用户取消订单");
    }

    @Override
    @Transactional
    public void confirmReceipt(Long id) {
        SaleOrder order = saleOrderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (!OrderStatusConstant.SHIPPING.equals(order.getStatus())) {
            throw new BusinessException("当前订单状态不允许确认收货");
        }

        order.setConfirmTime(LocalDateTime.now());
        recordStatusChange(order, OrderStatusConstant.COMPLETED, "consumer", "用户确认收货");
    }

    @Override
    @Transactional
    public void reviewOrder(Long id, SaleOrderReviewDTO dto) {
        SaleOrder order = saleOrderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        if (!OrderStatusConstant.COMPLETED.equals(order.getStatus())) {
            throw new BusinessException("只能评价已完成的订单");
        }

        if (order.getReviewTime() != null) {
            throw new BusinessException("订单已评价");
        }

        order.setRating(dto.getRating());
        order.setReviewContent(dto.getContent());
        order.setReviewAnonymous(dto.getAnonymous());
        order.setReviewTime(LocalDateTime.now());
        saleOrderMapper.updateOrderReview(order);
    }

    @Override
    public Result getById(Long id) {
        SaleOrder order = saleOrderMapper.findOrderById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return Result.success(order);
    }

    private String generateOrderNo() {
        return "SO" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }

    private boolean canCancel(String status) {
        return OrderStatusConstant.PENDING.equals(status) ||
               OrderStatusConstant.PAID.equals(status);
    }

    private void recordStatusChange(SaleOrder order, String newStatus, String operator, String remark) {
        // 记录状态变更日志
        SaleOrderStatusLog log = new SaleOrderStatusLog();
        log.setOrderId(order.getId());
        log.setOldStatus(order.getStatus());
        log.setNewStatus(newStatus);
        log.setOperator(operator);
        log.setRemark(remark);
        log.setCreateTime(LocalDateTime.now());
        saleOrderMapper.insertStatusLog(log);
        
        // 更新订单状态
        order.setStatus(newStatus);
        saleOrderMapper.updateOrderStatus(order);
    }
} 